package com.goldcontrol.cloudweb.quartz;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.goldcontrol.cloudweb.common.Constants;
import com.goldcontrol.cloudweb.controller.ApiController;
import com.goldcontrol.cloudweb.mapper.TemplateMapper;
import com.goldcontrol.cloudweb.model.JobEntity;
import com.goldcontrol.cloudweb.weixin.service.WeixinServiceApi;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class SchedulerManager {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    private JobListener scheduleListener;

    @Autowired
    ApiController apiController;

    @Autowired
    TemplateMapper templateMapper;

    /**
     * 开始定时任务
     * @param jobName
     * @param jobGroup
     * @throws SchedulerException
     */
    public void startJob(String cron,String jobName,String jobGroup,Class<? extends Job> jobClass) throws SchedulerException
    {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        if(scheduleListener==null){
            scheduleListener=new SchedulerListener();
            scheduler.getListenerManager().addJobListener(scheduleListener);
        }
        JobKey jobKey=new JobKey(jobName,jobGroup);
        if(!scheduler.checkExists(jobKey))
        {
            scheduleJob(cron,scheduler,jobName,jobGroup,jobClass);
        }
    }

    /**
     * 移除定时任务
     * @param jobName
     * @param jobGroup
     * @throws SchedulerException
     */
    public void deleteJob(String jobName,String jobGroup) throws SchedulerException
    {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey=new JobKey(jobName,jobGroup);
        scheduler.deleteJob(jobKey);
    }

    /**
     * 暂停定时任务
     * @param jobName
     * @param jobGroup
     * @throws SchedulerException
     */
    public void pauseJob(String jobName,String jobGroup) throws SchedulerException
    {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey jobKey=new JobKey(jobName,jobGroup);
        scheduler.pauseJob(jobKey);
    }

    /**
     * 恢复定时任务
     * @param jobName
     * @param jobGroup
     * @throws SchedulerException
     */
    public void resumeJob(String jobName,String jobGroup) throws SchedulerException
    {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        JobKey triggerKey=new JobKey(jobName,jobGroup);
        scheduler.resumeJob(triggerKey);
    }

    /**
     * 清空所有当前scheduler对象下的定时任务【目前只有全局一个scheduler对象】
     * @throws SchedulerException
     */
    public void clearAll() throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        scheduler.clear();
    }

    /**
     * 动态创建Job
     * 此处的任务可以配置可以放到properties或者是放到数据库中
     * Trigger:name和group 目前和job的name、group一致，之后可以扩展归类
     * @param scheduler
     * @throws SchedulerException
     */
    private void scheduleJob(String cron,Scheduler scheduler,String jobName,String jobGroup,Class<? extends Job> jobClass) throws SchedulerException{
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroup).build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup).withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail,cronTrigger);
    }


    //---自定义使用
    public void addJob(JobEntity jobEntity,Class<? extends Job> jobClass) throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        if(scheduleListener==null){
            scheduleListener=new SchedulerListener();
            scheduler.getListenerManager().addJobListener(scheduleListener);
        }
        JobKey jobKey=new JobKey(jobEntity.getJobName(),jobEntity.getGroupName());
        if(!scheduler.checkExists(jobKey))
        {
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobEntity.getJobName(), jobEntity.getGroupName()).build();
            jobDetail.getJobDataMap().put("pId",jobEntity.getProjectId());

            JSONObject itemObject;
            if (1 == jobEntity.getState()) {
                itemObject = this.getProjectItemInfo(jobEntity.getProjectId(), "启动命令");
            } else {
                itemObject = this.getProjectItemInfo(jobEntity.getProjectId(), "停止命令");
            }
            //获取开关机状态
            jobDetail.getJobDataMap().put("itemid", itemObject.getString("itemid"));
            jobDetail.getJobDataMap().put("devid", itemObject.getString("devid"));
            jobDetail.getJobDataMap().put("state", jobEntity.getState());
            Map<String, Object> param = new HashMap();
            param.put("projectId", jobEntity.getProjectId());
            if (1 == jobEntity.getState()) {
                param.put("item", "deviceOn");
            } else {
                param.put("item", "deviceOff");
            }
            String val = templateMapper.getProjectItemVal(param);
            jobDetail.getJobDataMap().put("val",val);

            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(jobEntity.getCronTime());
            CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(jobEntity.getJobName(), jobEntity.getGroupName()).withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail,cronTrigger);
        }
    }

    public void updateJob(JobEntity jobEntity){
        try {
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(jobEntity.getJobName(),jobEntity.getGroupName());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(jobEntity.getCronTime())) {
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                triggerBuilder.withIdentity(jobEntity.getJobName(),jobEntity.getGroupName());
                triggerBuilder.startNow();
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(jobEntity.getCronTime()).withMisfireHandlingInstructionDoNothing());
                trigger = (CronTrigger) triggerBuilder.build();
                scheduler.rescheduleJob(triggerKey, trigger);
            }
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void removeJob(JobEntity jobEntity) {
        try {
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(jobEntity.getJobName(),jobEntity.getGroupName());
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(JobKey.jobKey(jobEntity.getJobName(),jobEntity.getGroupName()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private JSONObject getProjectItemInfo(Object projectId,String item){
        String resposne = apiController.getProjectCurrentItemDataNew(Constants.TOKEN,projectId.toString());
        JSONObject jsonObject = JSON.parseObject(resposne).getJSONObject("data");
        for(String key : jsonObject.keySet()){
            if(key.equals(item)){
                return jsonObject.getJSONObject(key);
            }
        }
        return new JSONObject();
    }

}
